﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DevExpress.Xpf.Core;
using ThanNhanTao.Server;
using DevExpress.Xpf.Grid;
using DevExpress.XtraEditors.DXErrorProvider;
using ThanNhanTao.Report;
using ThanNhanTao.CommonControl;


namespace ThanNhanTao
{
    /// <summary>
    /// Interaction logic for frmPhieuChayThan.xaml
    /// </summary>
    public partial class frmPhieuChayThan : DXWindow
    {
        private static PhieuChayThanBll benhNhanBLL;
        private static BenhNhan bnTemple;
        private static List<PhieuChayThanDto> dsPhieu;
        private static List<PhieuChayThanDto> dsPhieuDaChay;
        private static List<PhieuChayThanDto> dsPhieuCapNhat;
        int lanChayThanNhoNhat;

        public frmPhieuChayThan()
        {
            InitializeComponent();
        }
        public frmPhieuChayThan(BenhNhan bnChayThan)
        {
            InitializeComponent();
            ThanNhanTaoGlobal.ListNgayXoa = new List<DateTime>();
            isLoder(bnChayThan);
        }
        private void isLoder(BenhNhan bnChayThan)
        {
            benhNhanBLL = new PhieuChayThanBll();
            bnTemple = new BenhNhan();
            getDmYeuCau();
            bnTemple = bnChayThan;
            SetThongTinBenhNhan();
            txtChayTiepTheo.Focus();
            txtChayTiepTheo.Text = "4";
        }
        private void getDmYeuCau()
        {
            List<Dm_YeuCau> dmYeuCau = benhNhanBLL.GetListYeuCau();
            //cboYeuCau.ItemsSource = dmYeuCau;
            foreach (Dm_YeuCau yc in dmYeuCau)
            {
                cboYeuCau.Items.Add(yc);
            }
            //cboYeuCau.DisplayMember = "TenYeuCau";
            //cboYeuCau.ValueMember = "MaYeuCau";
            cboYeuCau.DisplayMember = "MaYeuCau";
            cboYeuCau.ValueMember = "MaYeuCau";
            cboYeuCau.SelectedIndex = 0;
        }

        private int GetSoLanChay()
        {
            return benhNhanBLL.GetLanChay(bnTemple.IdBenhNhan);
        }

        private void SetThongTinBenhNhan()
        {
            try
            {
                lblThongTinBenhNhan.Content = bnTemple.Ho + " " + bnTemple.Ten + " - "
                    + (bnTemple.GioiTinh ? "Nam" : "Nữ") + " - " + bnTemple.Tuoi + " tuổi";
                int lanChayTruoc = GetSoLanChay();
                if (lanChayTruoc <= 0)
                {
                    txtLanChayTruoc.IsReadOnly = false;
                    txtLanChayTruoc.Focus();
                    txtLanChayTruoc.SelectAll();
                }
                txtLanChayTruoc.Text = lanChayTruoc.ToString();// GetSoLanChay().ToString();
            }
            catch
            {
            }
        }

        private void SetDsPhieuChayThan()
        {
            try
            {
                dsPhieu = new List<PhieuChayThanDto>();
                int lanChayNew = int.Parse(txtLanChayTruoc.Text.Trim());
                int chayToiDa = int.Parse(txtChayTiepTheo.Text.Trim()) + lanChayNew;
                int idMaxLanChayThanDB = benhNhanBLL.GetMaxIDChayThan();
                int idMaxChiDinh = benhNhanBLL.GetMaxIDChiDinh();
                Dm_YeuCau dmYeuCau = cboYeuCau.SelectedItem != null ? (Dm_YeuCau)cboYeuCau.SelectedItem : (Dm_YeuCau)cboYeuCau.EditValue;
                for (int i = lanChayNew; i < chayToiDa; i++)
                {
                    dsPhieu.Add(new PhieuChayThanDto
                                {
                                    LanChay = i + 1,
                                    NgayChay = ThanNhanTaoGlobal.NgayLamViec,
                                    NgayIn = ThanNhanTaoGlobal.NgayLamViec.ToShortDateString(),
                                    hoBN = bnTemple.Ho + " " + bnTemple.Ten,
                                    tuoi = bnTemple.Tuoi.ToString(),
                                    ChanDoan = bnTemple.Dm_ChanDoan.TenChanDoan,
                                    obChayThanNhanTao = new ChayThanNhanTao
                                                      {
                                                          IdChayThanNhanTao = idMaxLanChayThanDB + 1,
                                                          IdBenhNhan = bnTemple.IdBenhNhan,
                                                          SoLan = i + 1,
                                                          NgayChay = ThanNhanTaoGlobal.NgayLamViec,
                                                          DichChay = null
                                                      },
                                    obChiDinh = new ChiDinh
                                                      {
                                                          IdChiDinh = idMaxChiDinh + 1,
                                                          MaYeuCau = dmYeuCau.MaYeuCau,
                                                          MaDonViTinh = dmYeuCau.MaDonViTinh,
                                                          ChoNoiTru = false,
                                                          LaChayThan = true,
                                                          SoLuong = 1,
                                                          IdBenhNhan = bnTemple.IdBenhNhan,
                                                          IdChayThanNhanTao = idMaxLanChayThanDB,
                                                          NgayYeuCau = ThanNhanTaoGlobal.NgayLamViec,
                                                          GiaYeuCau = dmYeuCau.GiaYeuCau,
                                                          QuyBHYT = 0,
                                                          GiaKhac = 0
                                                      },
                                    delete = false
                                });
                }
                dsPhieu = dsPhieu.OrderByDescending(c => c.LanChay).ToList();
                dsPhieu[0].delete = true;
            }
            catch
            {
                DXMessageBox.Show("Xin nhập đầy đủ thông tin.", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void buttonDong_Click(object sender, RoutedEventArgs e)
        {
            base.Close();
        }

        private void buttonTaoPhieu_Click(object sender, RoutedEventArgs e)
        {
            SetDsPhieuChayThan();
            GridChayThanNhanTao.ItemsSource = dsPhieu;
            btnXoaRowDinhMuc.Visible = true;
            btnXoaRowDinhMucDaChay.Visible = false;
            cluPrint.Visible = false;
            buttonInPhieu.Visibility = Visibility.Visible;
            buttonInPhieuDaChay.Visibility = Visibility.Hidden;
            buttonCapNhat.Visibility = Visibility.Hidden;
            GridChayThanNhanTao.RefreshData();
        }

        private void btnDelRowDinhMuc_Click(object sender, RoutedEventArgs e)
        {
            PhieuChayThanDto chayThanDto = (PhieuChayThanDto)this.GridChayThanNhanTao.GetFocusedRow();
            if (chayThanDto.obChayThanNhanTao != null)
            {
                dsPhieu.Remove(chayThanDto);
            }
            if (dsPhieu.Count > 0)
            {
                dsPhieu[0].delete = true;
            }
            GridChayThanNhanTao.ItemsSource = dsPhieu;
            GridChayThanNhanTao.RefreshData();
        }

        private void btnDelRowDinhMucDaChay_Click(object sender, RoutedEventArgs e)
        {
            PhieuChayThanDto chayThanDto = (PhieuChayThanDto)this.GridChayThanNhanTao.GetFocusedRow();
            if (DXMessageBox.Show("Bạn muốn xóa phiếu chạy thận số:\n " + chayThanDto.LanChay + " ra khỏi danh sách ? \n (Xóa dữ liệu)", "Chú ý", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                if (chayThanDto.obChayThanNhanTao != null)
                {
                    if (benhNhanBLL.DeletePhieuChayThan(chayThanDto.obChayThanNhanTao, chayThanDto.obChiDinh))
                    {
                        dsPhieuDaChay.Remove(chayThanDto);
                        DXMessageBox.Show("Đã xóa phiếu chạy thận số: " + chayThanDto.LanChay + " thành công", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
                        txtLanChayTruoc.Text = GetSoLanChay().ToString();
                        ThanNhanTaoGlobal.IdBenhNhanXoa = bnTemple.IdBenhNhan;
                        ThanNhanTaoGlobal.ListNgayXoa.Add(chayThanDto.obChiDinh.NgayYeuCau);
                    }
                }
                if (dsPhieuDaChay.Count > 0)
                {
                    dsPhieuDaChay[0].delete = true;
                }
                GridChayThanNhanTao.ItemsSource = dsPhieuDaChay;
                GridChayThanNhanTao.RefreshData();
            }
        }

        private void buttonInPhieu_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LuuDuLieu();
                PrintPhieuChayTan();
            }
            catch { }
        }
        private void PrintPhieuChayTan()
        {
            rptPhieuChayThan rptChay = new rptPhieuChayThan();
            setNgayLaiPhieu();
            rptChay.SetThongTinHeader(dsPhieu[0].hoBN, dsPhieu[0].tuoi, dsPhieu[0].NgayChay, dsPhieu[0].LanChay, dsPhieu[0].ChanDoan);
            dsPhieu.RemoveAt(0);
            rptChay.DataSource = dsPhieu;
            rptChay.SetThongTin();
            ReportCommonWindow windowReport = new ReportCommonWindow(rptChay);
            windowReport.Title = "Phiếu in chạy thận";
            windowReport.ShowDialog();
        }

        private void setNgayLaiPhieu()
        {
            for (int i = 1; i < dsPhieu.Count; i++)
            {
                dsPhieu[i].NgayIn = "";
            }
        }

        private void LuuDuLieu()
        {

            int soLan = benhNhanBLL.GetLanChay(bnTemple.IdBenhNhan);
            if (soLan <= 0)
            {
                soLan = int.Parse(txtLanChayTruoc.Text.Trim());
            }
            dsPhieu = dsPhieu.OrderBy(c => c.LanChay).ToList();
            foreach (PhieuChayThanDto phieuct in dsPhieu)
            {
                try
                {
                    phieuct.obChayThanNhanTao.SoLan = soLan + 1;
                    phieuct.obChayThanNhanTao.NgayChay = phieuct.NgayChay;
                    phieuct.obChiDinh.NgayYeuCau = phieuct.NgayChay;
                    benhNhanBLL.AddPhieuChayThan(phieuct.obChayThanNhanTao, phieuct.obChiDinh);
                    soLan++;
                }
                catch
                {

                }
            }
            btnXoaRowDinhMuc.Visible = false;
            txtLanChayTruoc.Text = GetSoLanChay().ToString();
        }

        private void UpdateDuLieu()
        {
            foreach (PhieuChayThanDto phieuct in dsPhieuCapNhat)
            {
                try
                {
                    phieuct.obChayThanNhanTao.NgayChay = phieuct.NgayChay;
                    phieuct.obChiDinh.NgayYeuCau = phieuct.NgayChay;
                    phieuct.obChayThanNhanTao.SoLan = phieuct.LanChay;
                    benhNhanBLL.UpdatePhieuChayThan(phieuct.obChayThanNhanTao, phieuct.obChiDinh);
                }
                catch
                {
                    DXMessageBox.Show("Cập nhật không thành công", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
            DXMessageBox.Show("Cập nhật thành công", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
            dsPhieuCapNhat = new List<PhieuChayThanDto>();
        }

        private void buttonCacPhieuDaChay_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                dsPhieuDaChay = new List<PhieuChayThanDto>();
                dsPhieuDaChay = benhNhanBLL.GetListPhieuChayThan(bnTemple.IdBenhNhan, out lanChayThanNhoNhat).OrderByDescending(c => c.LanChay).ToList();
                dsPhieuDaChay[0].delete = true;
                GridChayThanNhanTao.ItemsSource = dsPhieuDaChay;
                btnXoaRowDinhMuc.Visible = false;
                btnXoaRowDinhMucDaChay.Visible = true;
                cluPrint.Visible = true;
                txtLanChayTruoc.Text = GetSoLanChay().ToString();
                buttonInPhieu.Visibility = Visibility.Hidden;
                buttonInPhieuDaChay.Visibility = Visibility.Visible;
                //buttonCapNhat.Visibility = Visibility.Visible;
                dsPhieuCapNhat = new List<PhieuChayThanDto>();
            }
            catch
            {
            }
        }

        private void cluNgayChay_Validate(object sender, GridCellValidationEventArgs e)
        {
            try
            {
                if (e.Column.FieldName == "NgayChay")
                {
                    if (!btnXoaRowDinhMuc.Visible)
                    {
                        buttonCapNhat.Visibility = Visibility.Visible;
                    }
                    //if (e.Value == null || this.Convert((DateTime)e.Value) - this.Convert(DateTime.Now) < 0)
                    //{
                    //    e.IsValid = false;
                    //    e.SetError(String.Format("Ngày phát nhỏ hơn ngày hiện tại.", "Thông tin", "0"), ErrorType.Warning);
                    //}

                    PhieuChayThanDto phieuBn = (PhieuChayThanDto)GridChayThanNhanTao.GetFocusedRow();
                    if (phieuBn != null)
                    {
                        DsCapNhat(phieuBn);
                    }
                }
            }
            catch { }

        }

        private void DsCapNhat(PhieuChayThanDto capNhat)
        {
            bool themVao = false;
            if (dsPhieuCapNhat.Count < 0)
            {
                dsPhieuCapNhat.Add(capNhat);
            }
            else
            {
                for (int i = 0; i < dsPhieuCapNhat.Count; i++)
                {
                    if (dsPhieuCapNhat[i].obChayThanNhanTao.IdChayThanNhanTao == capNhat.obChayThanNhanTao.IdChayThanNhanTao)
                    {
                        dsPhieuCapNhat[i] = capNhat;
                        themVao = true;
                        break;
                    }
                }
                if (themVao == false)
                {
                    dsPhieuCapNhat.Add(capNhat);
                }
            }
        }


        private Int32 Convert(DateTime ngay)
        {
            return (ngay.Year * 10000 + ngay.Month * 100 + ngay.Day);
        }

        private void buttonCapNhat_Click(object sender, RoutedEventArgs e)
        {
            UpdateDuLieu();
        }

        private void buttonInPhieuDaChay_Click(object sender, RoutedEventArgs e)
        {
            PrintPhieuChayTanDaDung();
        }
        private void PrintPhieuChayTanDaDung()
        {
            try
            {
                if (dsPhieuDaChay.Count > 0)
                {
                    rptPhieuChayThan rptChay = new rptPhieuChayThan();
                    List<PhieuChayThanDto> dsChayok = dsPhieuDaChay.Where(c => c.PrintPhieu == true).OrderBy(d => d.LanChay).ToList();
                    //setNgayLaiPhieuDaDung();
                    for (int i = 0; i < dsChayok.Count; i++)
                    {
                        dsChayok[i].NgayIn = string.Format("{0:dd/MM/yyyy}", dsChayok[i].NgayChay);
                    }
                    rptChay.SetThongTinHeader(bnTemple.Ho + " " + bnTemple.Ten, bnTemple.Tuoi.ToString(), dsChayok[0].NgayChay, dsChayok[0].LanChay, dsChayok[0].ChanDoan);
                    dsChayok.RemoveAt(0);
                    rptChay.DataSource = dsChayok;
                    rptChay.SetThongTin();
                    ReportCommonWindow windowReport = new ReportCommonWindow(rptChay);
                    windowReport.Title = "Phiếu in chạy thận";
                    windowReport.ShowDialog();
                }
            }
            catch
            {
            }
        }

        private void setNgayLaiPhieuDaDung()
        {
            for (int i = 1; i < dsPhieuDaChay.Count; i++)
            {
                dsPhieuDaChay[i].NgayIn = "";
            }
        }

        private void cluLanChay_Validate(object sender, GridCellValidationEventArgs e)
        {
            try
            {
                if (e.Column.FieldName == "LanChay")
                {
                    if (!btnXoaRowDinhMuc.Visible)
                    {
                        buttonCapNhat.Visibility = Visibility.Visible;
                    }
                    if (e.Value == null || e.Value is int)
                    {
                        e.IsValid = false;
                        e.SetError(String.Format("Không phải là số.", "Thông tin", "0"), ErrorType.Warning);
                    }
                    PhieuChayThanDto phieuBn = (PhieuChayThanDto)GridChayThanNhanTao.GetFocusedRow();
                    if (phieuBn != null)
                    {
                        if (phieuBn.LaLanChayThanNhoNhat)
                        {
                            int lanChayThanNhoNhatThayDoi = Int32.Parse(e.Value.ToString());
                            int soLanTang = lanChayThanNhoNhatThayDoi - lanChayThanNhoNhat;
                            foreach (var item in dsPhieuDaChay)
                            {
                                if (!item.LaLanChayThanNhoNhat)
                                    item.LanChay += soLanTang;
                                DsCapNhat(item);
                            }
                            lanChayThanNhoNhat = lanChayThanNhoNhatThayDoi;
                            GridChayThanNhanTao.RefreshData();
                        }
                        else
                        {
                            DsCapNhat(phieuBn);
                        }

                    }
                }
            }
            catch { }
        }

        private bool checkNgayVaLanChay(PhieuChayThanDto chayThan)
        {
            foreach (PhieuChayThanDto ct in GridChayThanNhanTao.ItemsSource as List<PhieuChayThanDto>)
            {
                if (ct.obChayThanNhanTao.NgayChay.CompareTo(chayThan.obChayThanNhanTao.NgayChay) > 0
                    && ct.obChayThanNhanTao.SoLan < chayThan.LanChay)
                {
                    return false;
                }
            }
            return true;
        }

        private void TBvChayThan_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            try
            {
                if ((e.NewRow as PhieuChayThanDto) == null)
                    return;
                bool daHoanThanh = (e.NewRow as PhieuChayThanDto).LaLanChayThanNhoNhat;
                cluLanChay.ReadOnly = !daHoanThanh;
            }
            catch (Exception)
            {
            }
            
        }

    }


}
